<template>
  <div
    class="time-line-wrap"
    :data-left-number="wgybVisable ? '560px' : '450px'"
  >
    <div class="btn-type-wrap">
      <div
        class="btn-type-item"
        @click="changeBtn(item)"
        :class="timeJgActive === item && 'active'"
        v-for="item in btnArr"
        :key="item"
      >
        {{ item }}时
      </div>
    </div>
    <div class="time-wrap">
      <div class="retreat" @click="retreat()">
        <img src="../images/Previous.png" alt="" />
      </div>
      <div class="play suspend" @click="play()">
        <img v-if="timerId" src="../images/suspend.png" alt="" />
        <img v-if="!timerId" src="../images/play.png" alt="" />
      </div>
      <div class="forward" @click="forward()">
        <img src="../images/Next.png" alt="" />
      </div>
    </div>
    <div
      class="time-ticp-wrap"
      v-for="(item, index) in computedTimeValue"
      :key="index"
      v-show="timeActive == index"
    >
      <div class="top-warp">
        <div class="date">{{ item.time }}</div>
        <div class="timePeriod">
          {{ timePeriod[progressIndex - 1] }}
        </div>
      </div>

      <div class="time-ticp">
        <div class="item-wrap" @click="changeCurrentTime(index)">
          <div class="progress-bar">
            <div
              class="progress"
              :style="{
                width:
                  (progressIndex / item.date.length) * 100 - 0.5 < 0
                    ? 0 + '%'
                    : (progressIndex / item.date.length) * 100 - 0.5 + '%'
              }"
            ></div>
          </div>
          <div class="date-time">
            <div
              v-for="(val, ind) in item.date"
              :key="ind"
              :class="['item', index === timeIndex && 'active']"
              @click="jumpTimeIndex(ind)"
            >
              {{ val }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import dayjs from 'dayjs'
import { usePredictionStore } from '@/pages/conventional-fine-forecasting/store/store'
import apiList from '@/pages/conventional-fine-forecasting/api/api'
import { useRouter } from 'vue-router'
const router = useRouter()
console.log(router)

const predictionStore = usePredictionStore()
const gdskjcCurrentActive = computed(() => predictionStore.gdskjcCurrentActive)
const wgybVisable = inject('wgybVisable')
let btnArr = ref([1, 3, 6, 12, 24])
let timerId = inject('timerId')
let timeIndex = inject('timeIndex')
let timeJgActive = inject('timeJgActive')
let timeArr = inject('timeArr')
const dataList = ref([])
const timeActive = ref(0)
const progressIndex = ref(1)
const isForward = ref(false)
const isRetreat = ref(false)
const computedTimeValue = ref()
const timePeriod = ref([])
timeJgActive.value = btnArr.value[0]
useEventBus('update:rightLengend').on(data => {
  if (data === 'RH' || data === 'VIS') {
    btnArr.value = [3, 6, 12, 24]
    timeJgActive.value = 3
  } else {
    btnArr.value = [1, 3, 6, 12, 24]
    timeJgActive.value = 1
  }
})
const initData = async () => {
  timePeriod.value = []
  const { data } = await apiList.getTimerShaftAndchoroplethicMap({
    intervalHour: timeJgActive.value ? timeJgActive.value : 1,
    elementCode: gdskjcCurrentActive.value
  })
  for (let time of data.list) {
    const timeString = time.url.match(
      /(\d{4})(\d{2})(\d{2})(\d{2})-(\d{4})(\d{2})(\d{2})(\d{2})/
    )
    // 提取各个时间段
    const startYear = timeString[1]
    const startMonth = timeString[2]
    const startDay = timeString[3]
    const startTime = timeString[4]

    const endYear = timeString[5]
    const endMonth = timeString[6]
    const endDay = timeString[7]
    const endTime = timeString[8]

    // 格式化时间
    const formattedTime = `${startYear}-${startMonth}-${startDay} ${startTime}-${endYear}-${endMonth}-${endDay} ${endTime}`
    timePeriod.value.push(formattedTime)
  }
  computedTimeValue.value = []
  if (timeJgActive.value != 12 && timeJgActive.value != 24) {
    computedTimeValue.value = data.list.reduce((acc, curr) => {
      const month = curr.forecastTime.slice(4, 6)
      const day = curr.forecastTime.slice(6, 8)
      const dateObj = {
        time: `${month}月${day}日`,
        date: []
      }

      const existing = acc.find(item => item.time === `${month}月${day}日`)
      if (existing) {
        existing.date.push(curr.forecastTime.slice(-2))
      } else {
        dateObj.date.push(curr.forecastTime.slice(-2))
        acc.push(dateObj)
      }

      return acc
    }, [])
  } else {
    let timeList = []
    let dateObj = {
      time: '',
      date: []
    }
    for (let i = 0; i < data.list.length; i++) {
      const month = data.list[i].forecastTime.slice(4, 6)
      const day = data.list[i].forecastTime.slice(6, 8)
      timeList.push(`${month}月${day}日`)
      dateObj.time = timeList[0] + '-' + timeList[timeList.length - 1]
      dateObj.date.push(data.list[i].forecastTime.slice(-2))
    }
    computedTimeValue.value = [dateObj]
  }
  timeActive.value = 0
}

const jumpTimeIndex = index => {
  let flag = timerId.value
  if (flag) {
    clearInterval(timerId.value)
    timerId.value = null
    progressIndex.value = index + 1
    predictionStore.timerIndex = progressIndex.value
  } else {
    progressIndex.value = index + 1
    predictionStore.timerIndex = progressIndex.value
  }
}
const play = () => {
  //播放暂停按钮
  if (computedTimeValue.length < 2) return
  if (!timerId.value) {
    playTimer()
  } else {
    clearInterval(timerId.value)
    timerId.value = null
  }
}
const playTimer = () => {
  isRetreat.value = false
  isForward.value = false
  //执行播放定时器
  timerId.value = setInterval(() => {
    progressIndex.value++
    console.log(timePeriod.value)
    timePeriod.value[progressIndex.value]
    console.log(progressIndex.value)

    predictionStore.timerIndex = progressIndex.value
    if (
      progressIndex.value ===
      computedTimeValue.value[timeActive.value].date.length
    ) {
      if (timeActive.value + 1 == computedTimeValue.value.length) {
        progressIndex.value =
          computedTimeValue.value[timeActive.value].date.length
        predictionStore.timerIndex =
          computedTimeValue.value[timeActive.value].date.length
        clearInterval(timerId.value)
        timerId.value = null
      } else {
        setTimeout(() => {
          timeActive.value += 1
          predictionStore.timerIndex -= 2
          progressIndex.value = 0
        }, 500)
      }
    }
  }, 2000)
}
const retreat = () => {
  //退后一个
  //先清除定时器 修改当前下标 重新执行定时器
  if (isRetreat.value) return
  let flag = timerId.value
  if (flag) {
    clearInterval(timerId.value)
    timerId.value = null
    progressIndex.value -= 1
  } else {
    predictionStore.timerIndex == 0
      ? (predictionStore.timerIndex = 0)
      : predictionStore.timerIndex--
    progressIndex.value == 0 ? (progressIndex.value = 0) : progressIndex.value--
    if (timeActive.value === 0 && progressIndex.value == 0) {
      isRetreat.value = true
    } else {
      if (timeActive.value != 0 && progressIndex.value == 0) {
        timeActive.value--
        progressIndex.value =
          computedTimeValue.value[timeActive.value].date.length
      }
    }
  }
}
const forward = () => {
  //前进一个
  //先清除定时器 修改当前下标 重新执行定时器
  if (isForward.value) return
  let flag = timerId.value
  if (flag) {
    clearInterval(timerId.value)
    timerId.value = null
    progressIndex.value += 1
  } else {
    progressIndex.value += 1
    predictionStore.timerIndex = progressIndex.value
    if (
      timeActive.value + 1 == computedTimeValue.value.length &&
      progressIndex.value ==
        computedTimeValue.value[timeActive.value].date.length
    ) {
      progressIndex.value =
        computedTimeValue.value[timeActive.value].date.length
      isForward.value = true
    } else {
      if (
        progressIndex.value >
        computedTimeValue.value[timeActive.value].date.length
      ) {
        timeActive.value++
        predictionStore.timerIndex -= 1
        progressIndex.value = 1
      }
    }
  }
}
const changeCurrentTime = index => {
  let flag = timerId.value
  if (flag) clearInterval(timerId.value)
  timeIndex.value = index
  if (flag) playTimer()
}
const changeBtn = item => {
  timeJgActive.value = item
  predictionStore.timerInterval = item
  timeIndex.value = 0
  progressIndex.value = 1
  predictionStore.timerIndex = 0
  initData()
  if (timerId.value) {
    clearInterval(timerId.value)
    timerId.value = null
  }
}
onMounted(() => {
  initData()
  gdskjcCurrentActive.value = 'RAIN'
})
watch(
  () => gdskjcCurrentActive.value,
  () => {
    if (timerId.value) {
      clearInterval(timerId.value)
      timerId.value = null
      progressIndex.value = 1
      predictionStore.timerIndex = 0
      timeActive.value = 0
    } else {
      progressIndex.value = 1
      predictionStore.timerIndex = 0
      timeActive.value = 0
    }
    initData()
  }
)
watch(
  () => window.location.hash == '#/conventional-fine-forecasting',
  () => {
    clearInterval(timerId.value)
    timerId.value = null
  },
  { deep: true, immediate: true }
)
onUnmounted(() => {
  clearInterval(timerId.value)
  timerId.value = null
})
</script>
<style lang="scss" scoped>
.time-line-wrap {
  --left-number: calc(var(--left-number-value) * 1px);
  position: absolute;
  left: calc(50% - var(--left-number));
  top: 10px;
  width: 919px;
  height: 70px;
  background: rgba(0, 13, 35, 0.59);
  box-shadow: 0px 0px 6px 1px rgba(0, 204, 255, 0.77),
    inset 0px 0px 14px 1px #00ccff;
  border-radius: 4px 4px 4px 4px;
  border: 1px solid #2c96cd;
  z-index: 1200;
  cursor: default;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 0 15px;
  box-sizing: border-box;
  font-size: 16px;
  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
  font-weight: 400;
  color: #ffffff;
  transition: all 0.5s;
  .btn-type-wrap {
    width: 288px;
    height: 36px;
    background: rgba(0, 13, 35, 0.68);
    box-shadow: inset 0px 0px 14px 1px #00ccff;
    border-radius: 22px 22px 22px 22px;
    display: flex;
    align-items: center;

    .btn-type-item {
      background: none;
      cursor: pointer;
      color: #ffffff;
      float: left;
      width: 65px;
      text-align: center;
      &.active {
        width: 65px;
        height: 36px;
        background: #006dff;
        box-shadow: inset 0px 0px 14px 1px #00ccff;
        border-radius: 22px 22px 22px 22px;
        text-align: center;
        line-height: 36px;
      }
    }
  }
  .time-wrap {
    // display: flex;
    // justify-content: flex-start;
    // align-items: center;
    width: 102px;
    margin-left: 5px;
    overflow: hidden;
    .retreat,
    .play,
    .suspend,
    .forward {
      width: 24px;
      height: 24px;
      background: #006dff;
      border-radius: 4px 4px 4px 4px;
      cursor: pointer;
      color: #fff;
      font-size: 14px;
      text-align: center;
      line-height: 24px;
      margin-right: 8px;
      float: left;
      img {
        width: 8px;
        height: 11px;
      }
    }
    .play,
    .suspend {
      img {
        width: 13px;
        height: 13px;
      }
    }
    .forward {
      margin-right: 14px;
    }
    .prev {
      width: 19px;
      height: 34px;
      background: #4056cc;
      margin: 0 5px;
      cursor: pointer;
      color: #fff;
      font-size: 16px;
      text-align: center;
      line-height: 34px;
    }

    .next {
      width: 19px;
      height: 34px;
      background: #4056cc;
      margin: 0 5px;
      cursor: pointer;
      color: #fff;
      font-size: 16px;
      text-align: center;
      line-height: 34px;
      transform: rotate(180deg);
    }
  }
  .time-ticp-wrap {
    width: 489px;
    height: 60px;
    float: left;
    overflow: hidden;
    .top-warp {
      width: 100%;
      display: flex;
      .date {
        width: 30%;
        text-align: center;
        line-height: 1.5;
        margin-right: 20px;
      }
      .timePeriod {
        line-height: 1.5;
      }
    }

    .time-ticp {
      width: 525px;
      height: 34px;
      .progress-bar {
        width: 489px;
        height: 10px;
        background: #1b3a52;
        border-radius: 4px 4px 4px 4px;
        .progress {
          width: 100%;
          height: 100%;
          background: linear-gradient(180deg, #00fff7 0%, #006fff 100%);
          border-radius: 4px 4px 4px 4px;
          transition: width 0.9s ease;
        }
      }
      .item-wrap {
        .date-time {
          width: 489px;
          display: flex;
          justify-content: space-between;
          .item {
            // width: 15.5px;
            box-sizing: border-box;
            // margin-right: 5px;
            margin-top: 8px;
            height: 18px;
            font-size: 14px;
            font-family: Microsoft YaHei-Regular, Microsoft YaHei;
            font-weight: 400;
            color: rgba(255, 255, 255, 0.59);
            line-height: 16px;
            cursor: pointer;
            // display: inline-block;
          }
        }
      }
    }
  }
}

.time-line-wrap[data-left-number='560px'] {
  --left-number-value: 590;
}

.time-line-wrap[data-left-number='450px'] {
  --left-number-value: 450;
}
</style>
